package com.elock.intf.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.dao.impl.DaoCenter;
import com.elock.base.core.util.ConvertUtil;

/**
 * Dao - 终端事件信息
 * @author 仁德
 */
@Repository("intfTerminalMessageEventDao")
public class IntfTerminalMessageEventDao extends DaoCenter {

	public Page<Map<String, Object>> findPage(Pageable pageable, Object[] args) {

		List<Object> list = new ArrayList<Object>();

		String companyCode = (String) args[0];
		String terminalNum = (String) args[1];
		String elockNum = (String) args[2];
		String saleOrgSn = (String) args[3];
		String startTime = (String) args[4];
		String endTime = (String) args[5];

		StringBuilder sql = new StringBuilder();
		sql.append("select m.*,p.status_desc,p.vol,p.jzdw,p.altitude,p.speed,");
		sql.append("p.direction,p.gps_time,ec.berth,ec.position,");
		sql.append("ec.car_number,wm.warning_message");
		sql.append(" from terminal_message_event m");
		sql.append(" left join company_info c on c.id=m.company_info_id");
		sql.append(" left join terminal t on m.terminal_num = t.terminal_num");
		sql.append(" left join elock e on m.elock_num = e.elock_num");
		sql.append(" and m.company_info_id=e.company_info_id");
		sql.append(" left join terminal_position p on m.uuid = p.uuid");
		sql.append(" left join elock_car ec on ec.elock_num = m.elock_num");
		sql.append(" and m.company_info_id=ec.company_info_id");
		sql.append(" left join warning_message wm on wm.uuid = m.uuid");
		sql.append(" where 1 = 1");
		if (companyCode != null) {
			sql.append(" and c.company_code=?");
			list.add(companyCode);
		}
		if (!ConvertUtil.isEmpty(terminalNum)) {
			sql.append(" and m.terminal_num like ?");
			list.add("%" + terminalNum + "%");
		}
		if (!ConvertUtil.isEmpty(elockNum)) {
			sql.append(" and m.elock_num like ?");
			list.add("%" + elockNum + "%");
		}
		if (!ConvertUtil.isEmpty(startTime)) {
			sql.append(" and m.event_time >= ?");
			list.add(startTime + " 00:00:00");
		}
		if (!ConvertUtil.isEmpty(endTime)) {
			sql.append(" and m.event_time < ?");
			list.add(endTime + " 24:00:00");
		}
		if (saleOrgSn != null) {
			sql.append(" and t.terminal_num in (select tso.terminal_num");
			sql.append(" from terminal_sale_org tso,sale_org so");
			sql.append(" where tso.sale_org_id=so.id and so.sn=?)");
			list.add(saleOrgSn);
		}
		sql.append(" order by m.id desc");

		Object[] objs = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			objs[i] = list.get(i);
		}

		Page<Map<String, Object>> page = getNativeDao().findPageMap(sql.toString(),
				objs,
				pageable);

		return page;
	}
}